<template>
  <div class="config-index">
    <div class="header-search-box shadow">
      <sec-form
        ref="secFormDom"
        :searchBox="searchBox"
        :span="8"
        :ruleForm="searchForm.data"
        :formData="searchForm.config"
        :optionData="optionData"
        @reset="fatchData(true)"
        @submitForm="fatchData(true)"
      >
      </sec-form>
    </div>
    <div class="scene-main tab-scene-main">
      <div class="new-file">
        <el-button v-if="admin" type="primary" icon="el-icon-plus" @click="handleNew">新建</el-button>
        <el-switch active-text="开启排序" v-model="onSortVal" style="margin: 0 10px 0 20px"></el-switch>
        <el-button v-show="onSortVal" type="primary" @click="saveSort">保存顺序</el-button>
      </div>

      <sec-table
        :loading="searchTable.loading"
        :tableData="searchTable.rows"
        :tableCol="searchTable.cols"
        :cellStyle="cellStyleFunc"
        ref="secTabel"
      >
        <template v-slot:operation="data">
          <el-button @click.native.prevent="handleView(data.data.row.id)" type="text">详情</el-button>
          <el-button v-if="admin" @click.native.prevent="handleEdit(data.data.row.id)" type="text"> 编辑</el-button>
          <el-button v-if="admin" @click.native.prevent="handleDel(data.data.row.id)" type="text"> 删除</el-button>
        </template>
      </sec-table>

      <el-pagination
        v-show="!onSortVal"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        background
        :page-sizes="pageSizes"
        :page-size="pageSize"
        :layout="layout"
        :total="totalSize"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import secForm from "components/formValidate/myForm";
import secTable from "components/table/comTable";
import { paginationMixin } from "common/js/mixin";
import { itemListAPI, indexSaveOrderApi, getAutoPreConditionsApi, getRiskNameApi } from "api/configApi.js";
import Sortable from "sortablejs";

export default {
  props: {},
  mixins: [paginationMixin],
  components: {
    secForm,
    secTable,
  },
  data() {
    return {
      optionData: {
        holeName: [],
      },
      searchBox: { span: 6, disabled: false },
      dragTableData: [], //存储拖拽的所有表格数据
      onSortVal: false,
      sortable: null, //Sortable插件 创建的对象
      admin: true,
      /**
       * 查询区域
       */
      searchForm: {
        /**
         * 查询表单数据
         */
        data: {
          name: "",
          scene: "",
          required: "",
          auto: "",
          time: "",
          enable: "",
          holeName: "",
          strategyType: "",
        },
        /**
         * 查询表单配置
         */
        config: [
          {
            type: "text",
            clearable: true,
            label: "指标名称",
            prop: "name",
          },
          {
            type: "select",
            clearable: true,
            label: "指标来源",
            prop: "scene",
            multiple: false,
            option: this.$store.state.dictionary[101003],
          },
          {
            type: "select",
            clearable: true,
            label: "是否必须",
            prop: "required",
            option: this.$store.state.dictionary[101004],
          },
          {
            type: "select",
            filterable: true,
            clearable: true,
            label: "是否自动化",
            prop: "auto",
            option: this.$store.state.dictionary[101004],
          },

          {
            type: "select",
            filterable: true,
            label: "策略类型",
            prop: "strategyType",
            option: this.$store.state.dictionary["strategyType"],
          },
          {
            type: "select",
            clearable: true,
            label: "是否启用",
            prop: "enable",
            option: this.$store.state.dictionary[101004],
          },
          { type: "select", label: "风险名称", prop: "holeName", filterable: true },
          { type: "datetimerange", span: 10, clearable: true, label: "更新时间", prop: "time" },
        ],
      },

      /***
       * 列表区域
       */
      searchTable: {
        //加载中
        loading: false,
        /***
         * 表格列
         */
        cols: [
          // { type: "selection", width: 60, align: "center" },
          { label: "指标ID", prop: "id", align: "center", width: 70 },
          {
            label: "指标名称",
            prop: "name",
            align: "center",
            width: "190px",
            showOverflowTooltip: false,
          },
          { label: "风险名称", prop: "holeName", align: "center" },
          {
            label: "指标来源",
            prop: "scene",
            align: "center",

            showOverflowTooltip: false,
            formatter: (row, column, cellValue, index) => {
              let t = "";
              if (Array.isArray(cellValue)) {
                cellValue.forEach((e) => {
                  t += this.utils.getDicLabel(101003, e) + ",";
                });
                return t.slice(0, -1);
              }
              return t;
            },
          },
          {
            label: "指标要求",
            prop: "reportItemContent",
            align: "left",
            width: 400,
            showOverflowTooltip: false,
          },
          {
            label: "修复建议",
            prop: "repairRecommend",
            align: "left",
            width: 400,
          },
          {
            label: "是否必须",
            prop: "required",
            align: "center",
            width: 100,
            showOverflowTooltip: true,
            formatter: (row, column, cellValue, index) => {
              return this.utils.getDicLabel(101004, cellValue);
            },
          },
          {
            label: "是否自动化",
            prop: "auto",
            align: "center",
            width: 100,
            showOverflowTooltip: true,
            formatter: (row, column, cellValue, index) => {
              return this.utils.getDicLabel(101004, cellValue);
            },
          },
          {
            label: "自动化前置条件",
            prop: "autoPreConditions",
            align: "center",
            width: 120,
            formatter: (row, column, cellValue, index) => {
              if (!cellValue) return "";
              let autoPerStrs = cellValue.split(",");
              console.log("autoPerStrs", autoPerStrs);
              if (autoPerStrs && autoPerStrs.length > 0) {
                let autoPerLable = autoPerStrs?.map((item) => {
                  console.log(item);
                  return this.autoPerConditions.find((list) => list.code == item)?.message;
                });
                return autoPerLable?.join(",");
              }
              return "-";
            },
          },
          {
            label: "创建人",
            prop: "creator",
            align: "center",
            width: 100,
            showOverflowTooltip: true,
          },
          {
            label: "创建时间",
            prop: "createTime",
            align: "center",
            width: 170,
            showOverflowTooltip: true,
          },
          {
            label: "更新人",
            prop: "operator",
            align: "center",
            width: 100,
            showOverflowTooltip: true,
          },
          {
            label: "更新时间",
            prop: "modifyTime",
            align: "center",
            width: 170,
            showOverflowTooltip: true,
          },
          {
            label: "操作",
            fixed: "right",
            columnType: "slot",
            prop: "operation",
            width: 150,
          },
        ],
        /**
         * 表格数据
         */
        rows: [],
      },

      //批量操作弹框
      opDialogVisible: false,

      // 编辑时需要的数据
      editData: {},
    };
  },
  computed: {},
  watch: {},
  async mounted() {
    await getAutoPreConditionsApi().then((res) => {
      this.autoPerConditions = res.data || [];
    });
    getRiskNameApi().then((res) => {
      let data = res.data;
      this.optionData.holeName = [];
      data.forEach((item) => {
        this.optionData.holeName.push({ label: item, value: item });
      });
    });
    this.initSortable();
    this.admin = this.utils.admin();
    await this.fatchData();
  },
  methods: {
    initSortable() {
      var that = this;
      const tbody = document.querySelector(".el-table__body-wrapper tbody");
      this.sortable = Sortable.create(tbody, {
        disabled: true,
        forceFallback: true, //解决拖动的时候不能滚动界面
        onEnd: function (evt) {
          let { newIndex, oldIndex } = evt;
          let oldData = that.dragTableData.splice(oldIndex, 1);
          that.dragTableData.splice(newIndex, 0, oldData[0]);
        },
      });
    },
    saveSort() {
      let loading = this.openLoading();
      indexSaveOrderApi({ list: this.getSortIds() }).then((res) => {
        loading.close();
        let state = this.message.state(res);
        if (!state) return;
        location.reload(); //刷新界面

        //watch的onSortVal改变去刷新列表 @todo 由于刷新列表之后数据没改变（后台返回的数据没问题），只有刷新界面才能改变 所有使用了上面的方式了
        // this.onSortVal = false;
      });
    },
    getSortIds() {
      return this.dragTableData.map((item) => {
        return item.id;
      });
    },
    cellStyleFunc() {
      if (this.onSortVal) {
        return { cursor: "move" };
      }
    },
    //获取数据
    fatchData(paginationReset) {
      //解决点击搜索或者重置的时候 改成第一页
      if (paginationReset) {
        this.paginationReset();
      }
      this.searchTable.loading = true;
      // let { name, scene, required, auto, time, strategyType, enable } = this.searchForm.data;
      let { time } = this.searchForm.data;
      itemListAPI({
        pageNum: this.page,
        pageSize: this.pageSize,
        modifyTimeStart: time[0] || "",
        modifyTimeEnd: time[1] || "",
        ...this.searchForm.data,
      }).then((res) => {
        this.searchTable.loading = false;
        this.totalSize = res.count;
        this.searchTable.rows = res.data;

        //排序数据
        let dragTableData = JSON.stringify(res.data);
        this.dragTableData = JSON.parse(dragTableData);
      });
    },

    // 每页显示N条
    handleSizeChange(e) {
      this.pageSize = e;
      this.fatchData();
    },
    //当前页改变
    handleCurrentChange(e) {
      this.page = e;
      this.fatchData();
    },
    // 新建
    handleNew() {
      this.$router.push({ path: "/config/form", query: {} });
    },
    // 详情
    handleView(id, index) {
      this.$router.push({ path: "/config/detail", query: { id: id } });
    },
    // 编辑
    handleEdit(id) {
      this.$router.push({ path: "/config/form", query: { id: id } });
    },
    // 删除
    handleDel(id) {
      this.$confirm("此操作不可恢复, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await this.$store.dispatch("config/itemDelete", { id: id });
          let state = this.message.state(res);
          if (!state) return;
          await this.fatchData();
        })
        .catch((e) => {});
    },
  },
  watch: {
    onSortVal(newVal) {
      if (newVal) {
        this.searchBox.disabled = true;
        this.sortable.options.disabled = false;
        this.pageSize = 1000; //为了获取指标列表所有数据
        this.$refs.secFormDom.resetForm(); //触发重置按钮 重新请求数据
      } else {
        this.searchBox.disabled = false; //搜索，重置按钮失效
        this.sortable.options.disabled = true; //拖拽失效
        this.pageSize = 10;
        this.fatchData(true); //刷新列表
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.config-index {
  .btn-table-op {
    text-align: right;
    margin: 0 0 10px 0;
  }
}
// ::v-deep .el-table__body td {
//   cursor: move;
// }
</style>
